const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const jwtkoa = require('koa-jwt')
const { isProd } = require('./utils/env')

// 密钥
const { JWT_SECRET_KEY } = require('./conf/secretKeys')

// 路由
const userWebApiRouter = require('./routes/webApi/user')
const registerRouter = require('./routes/index')
const errorRouter = require('./routes/view/error')


// error handler
let onerrorConf = {}
if (isProd) {
  onerrorConf = {
    redirect: '/error'
  }
}
onerror(app)

// koa-jwt
app.use(jwtkoa({
  secret: JWT_SECRET_KEY
}).unless({
  // 自定义那些目录忽略验证, /^\/jihuide\/account/ '/jihuide/account/login'
  path: [/^\/jihuide\/user/, '/jihuide/account/login', /^\/uploadFiles/, /^\/jihuidepc/]
}))

// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))

app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'ejs'
}))

if (isProd) {
  app.proxy = true
}

// 跨域设置
// app.use(convert(cors));
app.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', '*')
  await next()
})

// // logger 中间件的演示
// app.use(async (ctx, next) => {
//   const start = new Date()
//   await next()
//   const ms = new Date() - start
//   console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
// })

// routes
app.use(registerRouter())
app.use(userWebApiRouter.routes(), userWebApiRouter.allowedMethods())
app.use(errorRouter.routes(), errorRouter.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
})

module.exports = app
